import fs from 'fs';
import path from 'path';
import vue from 'rollup-plugin-vue';
import typescript from 'rollup-plugin-typescript2';
import postcss from 'rollup-plugin-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import alias from '@rollup/plugin-alias';

const componentDir = './src/components';
const cModuleNames = fs.readdirSync(path.resolve(componentDir));
const cModuleMap = cModuleNames.reduce(
  (prev, name) => ({ ...prev, [name]: `${componentDir}/${name}/index.vue` }),
  {}
);

export const createRollupConfig = (key) => ({
  external: ['@vue/composition-api', 'vue'],
  plugins: [
    alias({
      entries: [
        { find: '@', replacement: path.resolve(__dirname, 'src') },
        { find: '#', replacement: path.resolve(__dirname, 'src/components') },
      ],
    }),
    postcss({
      plugins: [
        autoprefixer({
          flexbox: true,
          grid: 'autoplace',
        }),
        cssnano,
      ],
      extract: `${key}/index.css`,
      autoModules: true,
    }),
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          module: 'ES2015',
          declaration: false,
        },
      },
    }),
    vue({ css: false }),
  ],
});

export default {
  input: {
    {{ projectName }}: './src/index.ts',
    ...cModuleMap,
  },
  output: {
    dir: 'build',
    format: 'esm',
    entryFileNames: '[name]/index.js',
    exports: 'named',
  },
  ...createRollupConfig('{{ projectName }}'),
};
